package com.bwie.server;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * Netty TCP服务器
 */
@Component
public class NettyTcpServer {
    private static final Logger logger = LoggerFactory.getLogger(NettyTcpServer.class);

    @Value("${netty.tcp.port:8089}")
    private int port;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    /**
     * 启动服务器
     */
    @PostConstruct
    public void start() throws Exception {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new TcpServerInitializer())
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            // 绑定端口，开始接收连接
            ChannelFuture future = bootstrap.bind(port).sync();
            logger.info("Netty TCP服务器启动成功，监听端口: {}", port);

            // 等待服务器关闭
            if (future.isSuccess()) {
                System.out.println("Netty TCP 服务器启动成功，监听端口: " + port);
            } else {
                System.err.println("Netty TCP 服务器启动失败！");
                System.err.println("原因: " + future.cause().getMessage());
            }
//            future.channel().closeFuture().sync();
        } finally {
//            workerGroup.shutdownGracefully();
//            bossGroup.shutdownGracefully();
        }
    }

    /**
     * 关闭服务器
     */
    @PreDestroy
    public void stop() {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        logger.info("Netty TCP服务器已关闭");
    }
}

